//
//  SearchViewController.m
//  LuckyRadio
//
//  Created by dllo on 15/11/23.
//  Copyright © 2015年 chenjun. All rights reserved.
//

#import "SearchViewController.h"
#import "LGCInforViewController.h"
#import "DetailTableViewCell.h"
#import "CollectionViewCell.h"
#import "GetConnection.h"
#import "SearchModel.h"
#import <MBProgressHUD.h>
#import <MJRefresh.h>

#define HEIGHT  [[UIScreen mainScreen]bounds].size.height / 667
#define WIDTH   [[UIScreen mainScreen]bounds].size.width / 375

@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain)UITableView *tableView;

@property (nonatomic, retain)NSMutableArray *arrayData;

@property (nonatomic, retain)NSMutableArray *arrayHot;

@property (nonatomic, retain)UISearchBar *searchBar;

@property (nonatomic, assign)NSInteger nextPage;

@property (nonatomic, retain)UILabel *labelHeader;

@property (nonatomic, copy)NSString *strheader;

@property (nonatomic, retain)UICollectionView *collectionView;

@property (nonatomic, retain)UIView *hot_view;

@property (nonatomic, retain)UIView *viewHeader;

@end

@implementation SearchViewController

- (void)dealloc
{
    [_arrayData release];
    [_arrayHot release];
    [_searchBar release];
    [_labelHeader release];
    [_viewHeader release];
    [_collectionView release];
    [_hot_view release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.hidesBackButton = YES;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor whiteColor];
    self.arrayData = [NSMutableArray array];
    self.arrayHot = [NSMutableArray array];
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 50 * WIDTH, 44 * HEIGHT)];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"搜索声音";
    self.searchBar.showsCancelButton = YES;
    self.navigationItem.titleView = self.searchBar;
    [_searchBar release];
    [self.searchBar becomeFirstResponder];
    [self.view addSubview:self.tableView];
    [self addFooter];
    [self getHotWord];
    [self createHotView];
}
/*****************   *****************/
- (void)createHotView
{
    self.hot_view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 500 * HEIGHT)];
    self.hot_view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.hot_view];
    [_hot_view release];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30 * WIDTH, 15 * HEIGHT, 150 * WIDTH, 20 * HEIGHT)];
    label.font = [UIFont systemFontOfSize:15];
    label.text = @"大家都在搜索";
    [self.hot_view addSubview:label];
    [label release];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10 * WIDTH, 50 * HEIGHT, self.view.frame.size.width - 20 * WIDTH, 150 * HEIGHT) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.hot_view addSubview:self.collectionView];
    [_collectionView release];
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"hotcell"];
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5 * WIDTH, 5 * HEIGHT, 10 * WIDTH, 5 * HEIGHT);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = [CollectionViewCell heightOfLabel:self.arrayHot[indexPath.row] andTextFont:[UIFont systemFontOfSize:15] andLabelHeight:30 * HEIGHT];
    if (indexPath.row == 0) {
        return CGSizeMake(50 * WIDTH, 30 * HEIGHT);
    }
    return CGSizeMake(20 * WIDTH + width, 30 * HEIGHT);
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arrayHot.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hotcell" forIndexPath:indexPath];
    cell.label_title.text = self.arrayHot[indexPath.row];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.searchBar.text = self.arrayHot[indexPath.row];
    [self searchBarSearchButtonClicked:self.searchBar];
}
- (void)getHotWord
{
    NSString *str = @"http://mobile.ximalaya.com/m/hot_search_keys?device=iPhone";
    [GetConnection startGETConnection:str parmaters:nil connectionBlock:^(id responseObject) {
        NSDictionary *dic = responseObject;
        self.arrayHot = [dic objectForKey:@"keys"];
        [self.collectionView reloadData];
        self.tableView.hidden = NO;
    }];
}
/*****************   *****************/
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailTableViewCell *cell = [DetailTableViewCell detailTableViewCellWith:tableView];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    SearchModel *searchModel = self.arrayData[indexPath.row];
    cell.searchModel = searchModel;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30 * HEIGHT;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.viewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30 * HEIGHT)];
       self.viewHeader.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.labelHeader = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 100 * WIDTH, 0, 100 * WIDTH, 30 * HEIGHT)];
    self.labelHeader.textColor = [UIColor grayColor];
    self.labelHeader.font = [UIFont systemFontOfSize:15];
    self.labelHeader.text = self.strheader;
    self.labelHeader.textAlignment = NSTextAlignmentCenter;
    [self.viewHeader addSubview:self.labelHeader];
    return _viewHeader;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115 * HEIGHT;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LGCInforViewController *infor = [LGCInforViewController shareLGCInformation];
    infor.strID = [self.arrayData[indexPath.row] ID];
    [self.navigationController pushViewController:infor animated:YES];
}
// 搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self addHeader];
    [self.hot_view setHidden:YES];
    [self.searchBar resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchText isEqualToString:@""]) {
        
        self.tableView.hidden = YES;
        
        [self.hot_view setHidden:NO];
    }
}
/***************** 懒加载 *****************/
- (UITableView *)tableView
{
    if (_tableView == nil) {
    _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.delegate = self;
    
    _tableView.dataSource = self;
    
    _tableView.separatorStyle = 0;
    }
    return _tableView;
}
// 刷新加载
- (void)addHeader
{
    [self.arrayData removeAllObjects];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.nextPage = 1;
        [self connection:self.nextPage];
    }];
    [self.tableView.mj_header beginRefreshing];
}
- (void)addFooter
{
    self.tableView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        self.nextPage += 1;
        [self connection:self.nextPage];
    }];
}
// 网络请求
- (void)connection:(NSInteger)nextPage
{
    NSString *str = self.searchBar.text;
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *strSearch = [NSString stringWithFormat:@"http://search.ximalaya.com/front/v1?condition=relation&core=album&device=iPhone&kw=%@&page=%ld&rows=20",str,nextPage];
    [GetConnection startGETConnection:strSearch parmaters:nil connectionBlock:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *array_docs = [[dic objectForKey:@"response"] objectForKey:@"docs"];
        self.strheader = [NSString stringWithFormat:@"共%@张专辑",[[dic objectForKey:@"response"] objectForKey:@"numFound"]];
        self.viewHeader.backgroundColor = [UIColor groupTableViewBackgroundColor];
        for (NSDictionary *temp in array_docs) {
            SearchModel *searchModel = [SearchModel modelWithDictionary:temp];
            [self.arrayData addObject:searchModel];
        }
        self.tableView.separatorStyle = 1;
        self.viewHeader.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [self.tableView reloadData];
        self.tableView.hidden = NO;
        if (self.arrayData.count != 0) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }else
        {
            MBProgressHUD *MBP = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [MBP show:YES];
             MBP.labelText = @"暂无搜索结果";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBP removeFromSuperview];
            });
            [self.tableView.mj_header endRefreshing];
        }
        self.viewHeader.backgroundColor = [UIColor groupTableViewBackgroundColor];
        if (array_docs.count == 0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
